<template>
  <div>{{ cValue }}</div>
</template>
<script setup lang="ts">
  import { computed, onMounted } from 'vue';
  import { useDictStore } from '@/store/modules/dict';
  import { defHttp } from '@/utils/http/axios';

  const dictStore = useDictStore();
  const props = defineProps({
    code: {
      type: String,
    },
    data: {
      type: Object,
      default() {
        return {};
      },
    },
    value: {
      // 值
      type: [String, Number, Array],
    },
    split: {
      // 分割符
      type: String,
      default: ',',
    },
    join: {
      // 连接符
      type: String,
      default: ',',
    },
    api: {
      // 接口请求对象
      type: [Function, String] as PropType<((...arg: any) => Promise<any>) | String>,
      default() {
        return () => {
          return new Promise((resolve) => {
            resolve([]);
          });
        };
      },
    },
    params: {
      type: Object,
      default() {
        return {};
      },
    },
    cacheKey: {
      type: String,
      default: '',
    },
    requestMethod: {
      type: String,
      default: 'post',
    },
  });
  /**
   * 获取包含的id
   */
  const getIncludeIds = () => {
    if (!props.value && props.value !== 0) {
      return [];
    }
    const arr: Array<any> = [];
    if (Array.isArray(props.value)) {
      arr.push(...props.value);
    } else {
      arr.push(...props.value.toString().split(props.split));
    }
    return arr;
  };
  /**
   * 获取缓存key
   */
  const getCacheKey = () => {
    let cacheKey = props.cacheKey;
    if (typeof props.api === 'string') {
      if (!cacheKey) {
        cacheKey = props.api as string;
      }
    }
    return cacheKey;
  };
  const cValue = computed(() => {
    if (!props.value && props.value !== 0) {
      return '';
    }
    const arr: Array<any> = getIncludeIds();
    const cacheKey = getCacheKey();
    const dictData = dictStore.getSelectData(cacheKey, {
      ...props.params,
      includeType: 2,
      includeIds: getIncludeIds(),
    });
    const res: Array<any> = [];
    arr.forEach((item) => {
      for (let i = 0; i < dictData.length; i++) {
        if (dictData[i].value == item) {
          res.push(dictData[i].label);
          break;
        }
        if (i == dictData.length - 1) {
          res.push(item);
        }
      }
    });

    return res.join(props.join);
  });
  onMounted(() => {
    let api: (...arg: any) => Promise<any>;
    const cacheKey = getCacheKey();
    if (typeof props.api === 'string') {
      api = (params: any) => {
        return defHttp[props.requestMethod]({ url: props.api as string, params });
      };
    } else {
      api = props.api as (...arg: any) => Promise<any>;
    }
    dictStore.select(
      api,
      {
        ...props.params,
        includeType: 2,
        includeIds: getIncludeIds(),
      },
      cacheKey,
    );
  });
</script>
<style lang="less" scoped></style>
